package com.hunzi.controller;

import com.hunzi.domain.*;
import com.hunzi.service.OrdersService;
import com.hunzi.utlis.CommonsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrdersService ordersService;

    @RequestMapping("/creat")
    public String creat(HttpServletRequest request , Model model){
        //1.当生成订单时用户必须先登录
        //将用户对象从session域中取出
        User user = (User) request.getSession ().getAttribute ( "user" );
        if (user==null){
            model.addAttribute ( "error" , "请您先登录之后在下订单" );
            return "login";
        }
        //2.从session中取出购物车
        Cart cart = (Cart) request.getSession ().getAttribute ( "cart" );
        //创建订单对象(订单与订单项)
        Orders order = new Orders ();
        order.setOid ( CommonsUtils.getUUID () );//设置订单编号
        order.setOrdertime ( new Date (  ) );//下单时间
        order.setTotal ( cart.getTotal () );//下单金额
        order.setUid ( user.getUid () );//下单人的id
        order.setState ( 1 );//默认为未付款

        //3.创建订单下订单项
        Map<Integer, CartItem> cartItems = cart.getCartItems ();
        //cartItems.entrySet ().for 遍历cartItems键值对，先把Map集合变成entrySet集合类型在遍历
        for (Map.Entry<Integer , CartItem> entry : cartItems.entrySet ()){

            //创建订单项（订单与商品）
            OrderItem orderItem = new OrderItem ();
            orderItem.setItemid ( CommonsUtils.getUUID () );//设置订单id
            orderItem.setCount ( entry.getValue ().getCount () );//设置该项的购买的数量
            orderItem.setId ( entry.getValue ().getItem ().getId () );//设置购买的商品id
            orderItem.setOid ( order.getOid () );//设置订单id
            orderItem.setItem ( entry.getValue ().getItem () );//设置商品对象
            //设置该项的小计
            orderItem.setSubtotal ( entry.getValue ().getSubtotal () );
            //向 订单中添加订单项
            order.getOrderItems ().add ( orderItem );
        }
        //生成订单
        ordersService.creatOrder ( order );
        //订单生成完毕，清空购物车
        request.getSession ().removeAttribute ( "cart" );

        //将订单回显到order页面
        model.addAttribute ( "order" , order );
        return "order";
    }
}
